package com.smile67.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smile67.common.constant.MessageConstant;
import com.smile67.common.constant.PasswordConstant;
import com.smile67.common.constant.StatusConstant;
import com.smile67.common.exception.AccountLockedException;
import com.smile67.common.exception.AccountNotFoundException;
import com.smile67.common.exception.PasswordErrorException;
import com.smile67.common.restult.PageResult;
import com.smile67.mapper.EmployeeMapper;
import com.smile67.pojo.dto.EmployeeDTO;
import com.smile67.pojo.dto.EmployeeLoginDTO;
import com.smile67.pojo.dto.EmployeePageQueryDTO;
import com.smile67.pojo.entity.Employee;
import com.smile67.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smile67
 * @since 2023-09-05
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1.根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2.处理各种异常情况（用户名不存在，密码错误，账号被锁定）
        //查找账号
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //将前端传回来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!(password.equals(employee.getPassword()))) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账户被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        return employee;
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //select * from employee limit 0,10
        Integer pageNo = employeePageQueryDTO.getPageNo();
        Integer pageSize = employeePageQueryDTO.getPageSize();
        String name = employeePageQueryDTO.getName();

        //构造分页构造器
        Page<Employee> page = new Page<>(pageNo, pageSize);

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<Employee>()
                .like(name != null, Employee::getName, name)//添加过滤条件
                .orderByDesc(Employee::getUpdateTime);//添加降序排列
        //执行查询
        page = page(page, wrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void update(Employee employee) {

        lambdaUpdate()
                .set(employee.getUserName() != null, Employee::getUserName, employee.getUserName())
                .set(employee.getName() != null, Employee::getName, employee.getName())
                .set(employee.getSex() != null, Employee::getSex, employee.getSex())
                .set(employee.getStatus() != null, Employee::getStatus, employee.getStatus())
                .set(employee.getPhone() != null, Employee::getPhone, employee.getPhone())
                .set(employee.getPassword() != null, Employee::getPassword, employee.getPassword())
                .set(employee.getIdNumber() != null, Employee::getIdNumber, employee.getIdNumber())
                .set(employee.getAvatar() != null, Employee::getAvatar, employee.getAvatar())
                .eq(employee.getId() != null, Employee::getId, employee.getId())
                .update();
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        //对象属性值拷贝
        Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);
        //设置状态：1正常 0锁定
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //保存
        save(employee);
    }
}
